<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DWF AI平台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            height: 100vh;
            overflow: hidden;
        }

        .container {
            display: flex;
            height: 100vh;
            backdrop-filter: blur(20px);
            background: rgba(255, 255, 255, 0.05);
        }

        .sidebar {
            width: 280px;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            border-right: 1px solid rgba(255, 255, 255, 0.2);
            padding: 24px 0;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
        }

        .logo {
            padding: 0 24px 32px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 24px;
        }

        .logo h1 {
            color: white; font-size: 24px; font-weight: 700;
            background: linear-gradient(45deg, #fff, #a8edea);
            -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;
        }

        .nav-menu { list-style: none; padding: 0 12px; flex-grow: 1; }
        .nav-item { margin-bottom: 8px; }
        .nav-link {
            display: flex; align-items: center; padding: 16px; color: rgba(255, 255, 255, 0.8);
            text-decoration: none; border-radius: 12px; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            font-weight: 500; position: relative; overflow: hidden;
        }
        .nav-link::before {
            content: ''; position: absolute; top: 0; left: -100%; width: 100%; height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
            transition: left 0.5s;
        }
        .nav-link:hover::before { left: 100%; }
        .nav-link:hover {
            background: rgba(255, 255, 255, 0.15); color: white; transform: translateX(4px);
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
        }
        .nav-link.active {
            background: rgba(255, 255, 255, 0.2); color: white;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        }
        .nav-icon { margin-right: 12px; font-size: 20px; width: 24px; text-align: center; }

        .main-content { flex: 1; padding: 32px; overflow-y: auto; background: #f0f2f5; }
        .header {
            background: #ffffff; padding: 24px 32px; border-radius: 16px;
            margin-bottom: 24px; border: 1px solid #e5e7eb;
        }
        .header h2 { color: #1f2937; font-size: 28px; font-weight: 600; margin-bottom: 8px; }
        .header p { color: #6b7280; font-size: 16px; }
        .header-actions { display: flex; align-items: center; gap: 12px; }

        .create-btn, .gemini-btn {
            background: linear-gradient(45deg, #8A92B2, #6C7596);
            color: white; font-size: 16px; padding: 0 24px;
            border-radius: 12px; box-shadow: 0 4px 16px rgba(108, 117, 150, 0.3);
            border: none; cursor: pointer; display: flex;
            align-items: center; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            height: 50px; box-sizing: border-box;
        }
        .create-btn:hover, .gemini-btn:hover {
            transform: translateY(-2px); box-shadow: 0 8px 25px rgba(108, 117, 150, 0.4);
        }
        .create-btn > span, .gemini-btn > span { margin-right: 8px; }

        .gemini-btn {
             background: linear-gradient(45deg, #5A92B2, #3C6596);
        }


        .dwf-env-select {
            padding: 0 16px; border-radius: 12px; border: 1px solid #d1d5db;
            background-color: #ffffff; color: #374151; font-size: 14px;
            font-family: inherit; height: 50px; box-sizing: border-box; min-width: 220px;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='%236b7280'%3E%3Cpath fill-rule='evenodd' d='M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z' clip-rule='evenodd' /%3E%3C/svg%3E");
            background-repeat: no-repeat; background-position: right 0.75rem center;
            background-size: 1.25em 1.25em; -webkit-appearance: none; -moz-appearance: none; appearance: none;
        }

        .data-card {
            background: #ffffff; border-radius: 16px; padding: 24px;
            border: 1px solid #e5e7eb; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative; overflow: hidden; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
            display: flex; flex-direction: column;
        }
        .data-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            border-color: #d1d5db;
        }
        .data-card-header { margin-bottom: 20px; }
        .data-card-title { display: flex; justify-content: space-between; align-items: center; }
        .data-card-title h3 { color: #1f2937; font-size: 20px; font-weight: 600; margin: 0; }
        .data-card-info { margin-bottom: 20px; flex-grow: 1; }
        .data-card-footer {
            display: flex; justify-content: space-between; align-items: center;
            margin-top: auto; padding-top: 16px; border-top: 1px solid #f0f2f5;
        }
        .data-card-actions { display: flex; gap: 8px; }

        .env-card::before {
            content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px;
            background: linear-gradient(90deg, #667eea, #764ba2);
        }
        .agent-card::before {
            content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px;
            background: linear-gradient(90deg, #10b981, #059669);
        }
        .mcp-card::before {
            content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px;
            background: linear-gradient(90deg, #06b6d4, #0891b2);
        }
        .env-card.default-env {
            border-left: 5px solid #667eea;
            box-shadow: 0 6px 15px rgba(102, 126, 234, 0.2);
        }
        .env-card.default-env::before {
            height: 4px; background: linear-gradient(90deg, #7f00ff, #e100ff);
        }

        .status-badge {
            display: flex; align-items: center; padding: 6px 12px;
            border-radius: 20px; font-size: 12px; font-weight: 500;
            text-transform: uppercase; letter-spacing: 0.5px;
        }
        .status-badge.running { background: rgba(34, 197, 94, 0.1); color: #16a34a; border: 1px solid rgba(34, 197, 94, 0.2); }
        .status-badge.pending { background: rgba(251, 191, 36, 0.1); color: #d97706; border: 1px solid rgba(251, 191, 36, 0.2); }
        .status-badge.maintenance, .status-badge.error { background: rgba(239, 68, 68, 0.1); color: #dc2626; border: 1px solid rgba(239, 68, 68, 0.2); }
        .status-badge.stopped { background: rgba(107, 114, 128, 0.1); color: #4b5563; border: 1px solid rgba(107, 114, 128, 0.2); }

        .status-dot {
            width: 8px; height: 8px; border-radius: 50%;
            margin-right: 8px; animation: pulse 2s infinite;
        }
        .status-badge.running .status-dot { background: #22c55e; }
        .status-badge.pending .status-dot { background: #fbbf24; }
        .status-badge.maintenance .status-dot, .status-badge.error .status-dot { background: #ef4444; }
        .status-badge.stopped .status-dot { background: #6b7280; animation: none; }

        .toggle-switch { position: relative; display: inline-block; width: 50px; height: 26px; }
        .toggle-switch input { opacity: 0; width: 0; height: 0; }
        .slider {
            position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0;
            background-color: #ccc; transition: .4s; border-radius: 26px;
        }
        .slider:before {
            position: absolute; content: ""; height: 20px; width: 20px;
            left: 3px; bottom: 3px; background-color: white;
            transition: .4s; border-radius: 50%;
        }
        input:checked + .slider { background-color: #22c55e; }
        input:focus + .slider { box-shadow: 0 0 1px #22c55e; }
        input:checked + .slider:before { transform: translateX(24px); }

        .info-item {
            display: flex; align-items: center; margin-bottom: 12px;
            padding: 8px 0; border-bottom: 1px solid #f0f2f5;
        }
        .info-item:last-child { margin-bottom: 0; border-bottom: none; }
        .info-item-content {
            display: flex; align-items: center; color: #6b7280;
            font-size: 14px; white-space: nowrap; margin-right: auto; /* Pushes value to the right */
        }
        .info-item-content .icon {
            margin-right: 8px; font-size: 16px;
            color: #6b7280; line-height: 1;
        }
        .info-label { color: #6b7280; font-size: 14px; white-space: nowrap; }
        .info-value {
            color: #374151; font-weight: 500;
            font-family: 'SF Mono', 'Monaco', 'Cascadia Code', monospace;
            background: #f9fafb;
            padding: 4px 8px; border-radius: 6px; font-size: 13px;
            text-align: right; margin-left: 16px;
            display: flex;
            align-items: center;
            word-break: break-all; /* Allow long URLs to wrap */
        }
        .info-value .url-text { /* Span for the URL text itself for potential ellipsis */
            overflow: hidden;
            text-overflow: ellipsis;
            /* white-space: nowrap; -- Commented out to allow wrapping first */
        }
        .info-value.pill {
            background-color: #e0e7ff; color: #4338ca;
            font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'Segoe UI', Roboto, sans-serif;
            font-weight: 500; padding: 3px 10px;
            word-break: normal; /* Reset for pills */
        }
        .copy-icon {
            margin-left: 8px;
            cursor: pointer;
            font-size: 14px;
            color: #6b7280;
            flex-shrink: 0; /* Prevent copy icon from shrinking */
        }
        .copy-icon:hover {
            color: #374151;
        }


        .action-btn {
            width: 36px; height: 36px; border: none; border-radius: 8px; cursor: pointer;
            transition: all 0.3s ease; display: flex; align-items: center; justify-content: center;
            font-size: 16px; position: relative; overflow: hidden;
        }
        .edit-btn { background: rgba(59, 130, 246, 0.1); color: #3b82f6; border: 1px solid rgba(59, 130, 246, 0.2); }
        .edit-btn:hover { background: rgba(59, 130, 246, 0.2); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2); }
        .delete-btn { background: rgba(239, 68, 68, 0.1); color: #ef4444; border: 1px solid rgba(239, 68, 68, 0.2); }
        .delete-btn:hover { background: rgba(239, 68, 68, 0.2); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(239, 68, 68, 0.2); }

        .debug-btn {
            background: rgba(16, 185, 129, 0.1);
            color: #059669;
            border: 1px solid rgba(16, 185, 129, 0.2);
        }
        .debug-btn:hover {
            background: rgba(16, 185, 129, 0.2);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(16, 185, 129, 0.2);
        }
        /* New Log button style */
        .log-btn {
            background: rgba(245, 158, 11, 0.1); /* Amber/Yellow tint */
            color: #d97706; /* Darker Amber/Yellow */
            border: 1px solid rgba(245, 158, 11, 0.2);
        }
        .log-btn:hover {
            background: rgba(245, 158, 11, 0.2);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(245, 158, 11, 0.2);
        }


        .set-default-btn {
            padding: 6px 12px; font-size: 12px; font-weight: 500;
            border: 1px solid #374151; color: #374151;
            background-color: transparent; border-radius: 20px;
            cursor: pointer; transition: all 0.3s ease;
            display: flex; align-items: center;
        }
        .set-default-btn .icon { margin-right: 4px; }
        .set-default-btn:hover { background-color: rgba(55, 65, 81, 0.1); }
        .env-card.default-env .set-default-btn {
            background-color: #667eea; border-color: #667eea; color: white;
        }

        /* Grid Layouts */
        .environments-grid, .agents-grid, .mcp-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(340px, 370px));
            gap: 24px; margin-top: 24px; justify-content: start;
        }

        /* MODAL & DRAWER STYLES */
        .modal-overlay, .drawer-overlay {
            display: none; position: fixed; z-index: 1000; left: 0; top: 0;
            width: 100%; height: 100%;
            background-color: rgba(0,0,0,0.6); backdrop-filter: blur(5px);
        }
        .modal-overlay.active, .drawer-overlay.active {
            display: flex;
        }

        .modal-content {
            background-color: #ffffff; margin: auto;
            padding: 24px 32px; border: 1px solid #d1d5db; border-radius: 16px;
            width: 90%; max-width: 600px; /* Default max-width */
            box-shadow: 0 10px 25px rgba(0,0,0,0.1), 0 5px 10px rgba(0,0,0,0.05);
            animation: slideDownModal 0.3s ease-out;
            display: flex;
            flex-direction: column;
            max-height: 90vh;
        }
        .modal-content.large {
             max-width: 750px;
        }

        @keyframes slideDownModal {
            from { transform: translateY(-30px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        .modal-header {
            display: flex; justify-content: space-between; align-items: center;
            padding-bottom: 16px; border-bottom: 1px solid #e5e7eb; margin-bottom: 24px;
            flex-shrink: 0;
        }
        .modal-header h3 { color: #1f2937; font-size: 22px; font-weight: 600; }
        .close-btn {
            color: #9ca3af; font-size: 28px; font-weight: bold;
            background: none; border: none; cursor: pointer;
            padding: 0; line-height: 1;
        }
        .close-btn:hover, .close-btn:focus { color: #1f2937; }
        .modal-body {
            gap: 20px;
            overflow-y: auto;
            padding-right: 10px;
        }
        #mcpLogContent { /* Specific styling for log content area */
            white-space: pre-wrap;
            background-color: #1f2937; /* Dark background for logs */
            color: #e5e7eb; /* Light text for logs */
            font-family: 'SF Mono', 'Monaco', 'Cascadia Code', monospace;
            padding: 16px;
            border-radius: 8px;
            max-height: 60vh; /* Limit height */
            overflow-y: auto;
            font-size: 13px;
            line-height: 1.6;
        }

        .form-group { display: flex; flex-direction: column; margin-bottom: 20px; }
        .form-group:last-child { margin-bottom: 0; }

        .form-group label {
            font-size: 14px; color: #374151;
            margin-bottom: 8px; font-weight: 500;
        }
        .form-group input[type="text"],
        .form-group input[type="url"],
        .form-group input[type="number"],
        .form-group input[type="password"],
        .form-group textarea {
            padding: 12px 16px; border: 1px solid #d1d5db;
            border-radius: 8px; font-size: 14px; color: #1f2937;
            transition: border-color 0.2s ease, box-shadow 0.2s ease;
            font-family: inherit; width: 100%;
        }
        .form-group textarea { min-height: 80px; resize: vertical; }
        .form-group input:focus, .form-group textarea:focus {
            outline: none; border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
        }
        .form-group.inline { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        .modal-footer {
            display: flex; justify-content: flex-end; gap: 12px;
            padding-top: 24px; margin-top: 24px; border-top: 1px solid #e5e7eb;
            flex-shrink: 0;
        }
        .modal-btn {
            padding: 12px 24px; font-size: 14px; font-weight: 500;
            border-radius: 8px; border: none; cursor: pointer; transition: all 0.3s ease;
        }
        .modal-btn-primary {
            background: linear-gradient(45deg, #667eea, #764ba2); color: white;
        }
        .modal-btn-primary:hover { opacity: 0.9; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3); }
        .modal-btn-secondary {
            background-color: #e5e7eb; color: #374151; border: 1px solid #d1d5db;
        }
        .modal-btn-secondary:hover { background-color: #d1d5db; }
        /* END MODAL STYLES */

        /* AGENT CHAT DRAWER STYLES */
        .chat-drawer {
            position: fixed; top: 0; right: -450px;
            width: 420px; height: 100%;
            background-color: #ffffff; box-shadow: -5px 0 15px rgba(0,0,0,0.15);
            transition: right 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
            z-index: 1001; display: flex; flex-direction: column;
        }
        .chat-drawer.active { right: 0; }
        .chat-drawer-header {
            display: flex; justify-content: space-between; align-items: center;
            padding: 16px 20px; border-bottom: 1px solid #e5e7eb;
            background-color: #f9fafb;
        }
        .chat-drawer-header h3 { color: #1f2937; font-size: 18px; font-weight: 600; }
        .chat-drawer-body {
            flex-grow: 1; overflow-y: auto; padding: 16px;
            background-color: #f0f2f5; display: flex; flex-direction: column;
        }
        .chat-message {
            padding: 10px 14px; border-radius: 12px;
            margin-bottom: 10px; max-width: 80%;
            font-size: 14px; line-height: 1.5; word-wrap: break-word;
        }
        .chat-message.user {
            background-color: #667eea; color: white;
            align-self: flex-end; border-bottom-right-radius: 4px;
        }
        .chat-message.agent {
            background-color: #e5e7eb; color: #1f2937;
            align-self: flex-start; border-bottom-left-radius: 4px;
        }
        .chat-message.loading { color: #6b7280; font-style: italic; }
        .chat-drawer-footer {
            padding: 16px 20px; border-top: 1px solid #e5e7eb;
            background-color: #ffffff;
        }
        .chat-input-area { display: flex; gap: 10px; }
        .chat-input-area input[type="text"] {
            flex-grow: 1; padding: 12px 16px;
            border: 1px solid #d1d5db; border-radius: 8px; font-size: 14px;
        }
        .chat-input-area input[type="text"]:focus {
            outline: none; border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
        }
        /* END AGENT CHAT DRAWER STYLES */

        /* MCP Tree Config Styles */
        .tree-view {
            padding-left: 0;
            list-style-type: none;
        }
        .tree-view ul {
            padding-left: 20px;
            list-style-type: none;
            border-left: 1px dashed #ccc;
            margin-left: 7px;
        }
        .tree-view li {
            margin: 8px 0;
            position: relative;
        }
        .tree-view label {
            font-size: 14px;
            color: #374151;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
        }
        .tree-view input[type="checkbox"] {
            margin-right: 8px;
            width: 16px;
            height: 16px;
            accent-color: #667eea;
        }
        .tree-group-label {
            font-weight: 600;
            font-size: 15px;
            color: #1f2937;
            margin-bottom: 10px;
            display: block;
        }
        .tree-view-container {
             border: 1px solid #e5e7eb;
             padding: 16px;
             border-radius: 8px;
             background-color: #f9fafb;
             max-height: 200px;
             overflow-y: auto;
        }
        .form-section-title {
            font-size: 16px;
            font-weight: 600;
            color: #111827;
            margin-bottom: 12px;
            padding-bottom: 8px;
            border-bottom: 1px solid #e5e7eb;
        }


        .loading-indicator {
            display: inline-block; width: 16px; height: 16px;
            border: 2px solid rgba(255,255,255,0.3); border-radius: 50%;
            border-top-color: #fff; animation: spin 1s ease-in-out infinite;
            margin-left: 8px;
        }
        @keyframes spin { to { transform: rotate(360deg); } }


        @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }

        @media (max-width: 768px) {
            .container { flex-direction: column; }
            .sidebar { width: 100%; height: auto; padding: 16px 0; }
            .nav-menu { display: flex; overflow-x: auto; padding: 0 12px; }
            .nav-item { margin-bottom: 0; margin-right: 8px; flex-shrink: 0; }
            .main-content { padding: 16px; }
            .environments-grid, .agents-grid, .mcp-grid { grid-template-columns: 1fr; }

            .header { padding: 16px; }
            .header > div { flex-direction: column; align-items: flex-start; }
            .header-actions {
                margin-top: 16px; width: 100%;
                flex-direction: column; gap: 10px;
            }
            .dwf-env-select, .create-btn, .gemini-btn { width: 100%; }
            .create-btn, .gemini-btn { padding: 12px 18px; font-size: 15px; height: 46px; }
            .dwf-env-select { height: 46px; font-size: 15px; }
            .data-card-footer { flex-direction: column; align-items: stretch; gap: 10px; }
            .data-card-actions { justify-content: center; }
            .set-default-btn { width: 100%; justify-content: center; }
            .modal-content { width: 95%; padding: 20px; max-height: 85vh;}
            .modal-body { padding-right: 5px; /* Adjust for smaller scrollbar on mobile */ }
            .form-group.inline { grid-template-columns: 1fr; }
            .chat-drawer { width: 90%; right: -100%; /* Adjust for mobile */ }
            .chat-drawer.active { right: 0; }
        }
    </style>
</head>
<body>
    <div class="container">
        <nav class="sidebar">
            <div class="logo"><h1>DWF AI平台</h1></div>
            <ul class="nav-menu">
                <li class="nav-item"><a href="#" class="nav-link" onclick="switchTab('environment')"><span class="nav-icon">🌐</span>DWF环境管理</a></li>
                <li class="nav-item"><a href="#" class="nav-link" onclick="switchTab('mcp')"><span class="nav-icon">🔧</span>DWF MCP管理</a></li>
                <li class="nav-item"><a href="#" class="nav-link" onclick="switchTab('agents')"><span class="nav-icon">🤖</span>智能体广场</a></li>
            </ul>
        </nav>

        <main class="main-content">
            <div id="environment" class="tab-content" style="display: none;">
                <div class="header">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div><h2>DWF环境管理</h2><p>管理您的DWF实例环境，可以在不同环境之间进行切换</p></div>
                        <div class="header-actions">
                            <button class="create-btn" onclick="testConnect()">🔗 测试连接</button>
                            <button class="create-btn" onclick="openAddEnvModal()"><span>➕</span>添加环境</button>
                        </div>
                    </div>
                </div>
                <div class="environments-grid">
                    <div class="data-card env-card default-env" id="env-card-china-hedian-prod-001">
                        <div class="data-card-header"><div class="data-card-title"><h3>中国核电</h3><div class="status-badge running"><span class="status-dot"></span>连接成功</div></div></div>
                        <div class="data-card-info">
                            <div class="info-item"><span class="info-item-content"><span class="info-label">实例名称：</span></span><span class="info-value">china-hedian-prod-001</span></div>
                            <div class="info-item"><span class="info-item-content"><span class="info-label">实例地址：</span></span><span class="info-value">192.168.1.100:9090</span></div>
                        </div>
                        <div class="data-card-footer">
                             <button class="set-default-btn" onclick="setDefaultEnvironment('china-hedian-prod-001')"><span class="icon">⭐</span>已为默认</button>
                            <div class="data-card-actions">
                                <button class="action-btn edit-btn" onclick="editEnvironment('china-hedian-prod-001')" title="编辑">⚙️</button>
                                <button class="action-btn delete-btn" onclick="deleteEnvironment('china-hedian-prod-001')" title="删除">🗑️</button>
                            </div>
                        </div>
                    </div>
                    <div class="data-card env-card" id="env-card-tpms-test-001">
                        <div class="data-card-header"><div class="data-card-title"><h3>TPMS 项目</h3><div class="status-badge running"><span class="status-dot"></span>连接成功</div></div></div>
                        <div class="data-card-info">
                            <div class="info-item"><span class="info-item-content"><span class="info-label">实例名称：</span></span><span class="info-value">tpms-test-001</span></div>
                            <div class="info-item"><span class="info-item-content"><span class="info-label">实例地址：</span></span><span class="info-value">192.168.1.101:9090</span></div>
                        </div>
                         <div class="data-card-footer">
                            <button class="set-default-btn" onclick="setDefaultEnvironment('tpms-test-001')"><span class="icon">✩</span>设为默认</button>
                            <div class="data-card-actions">
                                <button class="action-btn edit-btn" onclick="editEnvironment('tpms-test-001')" title="编辑">⚙️</button>
                                <button class="action-btn delete-btn" onclick="deleteEnvironment('tpms-test-001')" title="删除">🗑️</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div id="agents" class="tab-content" style="display: none;">
                <div class="header">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div><h2>智能体广场</h2><p>发现、创建和管理您的AI智能体</p></div>
                        <div class="header-actions">
                            <select class="dwf-env-select" id="agentEnvSelect">
                                <option value="env1">中国核电 (prod-001)</option>
                                <option value="env2">TPMS 项目 (test-001)</option>
                            </select>
                            <button class="create-btn" onclick="createAgent()"><span>➕</span>创建智能体</button>
                        </div>
                    </div>
                </div>
                <div class="agents-grid">
                    <div class="data-card agent-card" data-agent-id="agent_cs_ai" data-agent-name="智能客服AI" data-agent-type="单Agent">
                        <div class="data-card-header"><div class="data-card-title"><h3>智能客服AI</h3></div></div>
                        <div class="data-card-info">
                            <div class="info-item"><span class="info-item-content"><span class="info-label">模型服务：</span></span><span class="info-value">openai-gpt4-turbo</span></div>
                            <div class="info-item"><span class="info-item-content"><span class="info-label">类型：</span></span><span class="info-value pill">单Agent</span></div>
                        </div>
                        <div class="data-card-footer">
                             <div></div>
                             <div class="data-card-actions">
                                <button class="action-btn debug-btn" onclick="openAgentChatDrawer('agent_cs_ai', '智能客服AI', '单Agent')" title="调试/对话">💬</button>
                                <button class="action-btn edit-btn" onclick="configureAgent('agent_cs_ai')" title="配置">⚙️</button>
                                <button class="action-btn delete-btn" onclick="deleteAgent('agent_cs_ai')" title="删除">🗑️</button>
                            </div>
                        </div>
                    </div>
                    <div class="data-card agent-card" data-agent-id="agent_code_review" data-agent-name="代码生成与审查流程" data-agent-type="多Agent">
                        <div class="data-card-header"><div class="data-card-title"><h3>代码生成与审查流程</h3></div></div>
                        <div class="data-card-info">
                            <div class="info-item"><span class="info-item-content"><span class="info-label">模型服务：</span></span><span class="info-value">deepseek-coder-v2</span></div>
                            <div class="info-item"><span class="info-item-content"><span class="info-label">类型：</span></span><span class="info-value pill">多Agent</span></div>
                        </div>
                        <div class="data-card-footer">
                            <div></div>
                            <div class="data-card-actions">
                                <button class="action-btn debug-btn" onclick="openAgentChatDrawer('agent_code_review', '代码生成与审查流程', '多Agent')" title="调试/对话">💬</button>
                                <button class="action-btn edit-btn" onclick="configureAgent('agent_code_review')" title="配置">⚙️</button>
                                <button class="action-btn delete-btn" onclick="deleteAgent('agent_code_review')" title="删除">🗑️</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div id="mcp" class="tab-content" style="display: none;">
                <div class="header">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div><h2>MCP管理</h2><p>配置和运行您的DWF MCP服务实例</p></div>
                        <div class="header-actions">
                            <select class="dwf-env-select" id="mcpEnvSelect">
                                <option value="env1">中国核电 (prod-001)</option>
                                <option value="env2">TPMS 项目 (test-001)</option>
                            </select>
                            <button class="create-btn" onclick="openCreateMcpModal()"><span>➕</span>创建DWF MCP</button>
                        </div>
                    </div>
                </div>
                <div class="mcp-grid">
                     <div class="data-card mcp-card">
                        <div class="data-card-header">
                            <div class="data-card-title">
                                <h3>通用知识库MCP</h3>
                                <label class="toggle-switch">
                                    <input type="checkbox" id="mcp_toggle_knowledge_base" onchange="toggleMcpStatus('mcp_knowledge_base', this.checked)" checked>
                                    <span class="slider"></span>
                                </label>
                            </div>
                        </div>
                        <div class="data-card-info">
                            <div class="info-item">
                                <span class="info-item-content"><span class="icon">🛠️</span><span class="info-label">Tools数量：</span></span>
                                <span class="info-value">15</span>
                            </div>
                            <div class="info-item">
                                <span class="info-item-content"><span class="icon">📚</span><span class="info-label">Resources数量：</span></span>
                                <span class="info-value">250</span>
                            </div>
                            <div class="info-item">
                                <span class="info-item-content"><span class="icon">💬</span><span class="info-label">Prompts数量：</span></span>
                                <span class="info-value">80</span>
                            </div>
                            <div class="info-item">
                                <span class="info-item-content"><span class="icon">🔗</span><span class="info-label">SSE URL：</span></span>
                                <span class="info-value">
                                    <span class="url-text" id="sseUrl_knowledge_base">http://localhost:8001/sse</span>
                                    <span class="copy-icon" onclick="copyToClipboard('sseUrl_knowledge_base')" title="复制URL">📋</span>
                                </span>
                            </div>
                        </div>
                        <div class="data-card-footer">
                             <div></div> <!-- Spacer for left side -->
                            <div class="data-card-actions">
                                <!-- MODIFIED: Added Log button -->
                                <button class="action-btn log-btn" onclick="viewMcpLogs('mcp_knowledge_base')" title="查看日志">📄</button>
                                <button class="action-btn edit-btn" onclick="configureMCP('mcp_knowledge_base')" title="配置">⚙️</button>
                                <button class="action-btn delete-btn" onclick="deleteMCP('mcp_knowledge_base')" title="删除">🗑️</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- Add Environment Modal -->
    <div id="addEnvModal" class="modal-overlay">
        <div class="modal-content">
            <div class="modal-header">
                <h3>添加新DWF环境</h3>
                <button class="close-btn" onclick="closeAddEnvModal()">&times;</button>
            </div>
            <form id="addEnvForm">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="envName">环境名称</label>
                        <input type="text" id="envName" name="envName" required>
                    </div>
                    <div class="form-group">
                        <label for="envKey">环境Key (实例名称)</label>
                        <input type="text" id="envKey" name="envKey" required>
                    </div>
                    <div class="form-group">
                        <label for="envDescription">环境描述</label>
                        <textarea id="envDescription" name="envDescription" rows="3"></textarea>
                    </div>
                     <button type="button" class="gemini-btn" id="generateEnvDescBtn" onclick="generateEnvironmentDescription()" style="margin-top: -10px; margin-bottom: 10px; width: auto; padding: 10px 15px; font-size: 14px;">
                        ✨ 生成描述
                        <span class="loading-indicator" style="display: none;"></span>
                    </button>
                    <div class="form-group">
                        <label for="envUrl">实例URL</label>
                        <input type="url" id="envUrl" name="envUrl" placeholder="http://example.com" required>
                    </div>
                    <div class="form-group inline">
                        <div>
                            <label for="modelerPort">Modeler服务端口</label>
                            <input type="number" id="modelerPort" name="modelerPort" value="9090" required>
                        </div>
                        <div>
                            <label for="appPort">App服务端口</label>
                            <input type="number" id="appPort" name="appPort" value="6060" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="envUsername">用户名</label>
                        <input type="text" id="envUsername" name="envUsername">
                    </div>
                    <div class="form-group">
                        <label for="envPassword">密码</label>
                        <input type="password" id="envPassword" name="envPassword">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="modal-btn modal-btn-secondary" onclick="closeAddEnvModal()">取消</button>
                    <button type="button" class="modal-btn modal-btn-primary" onclick="saveNewEnvironment()">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Agent Chat Drawer -->
    <div id="agentChatOverlay" class="drawer-overlay"></div>
    <div id="agentChatDrawer" class="chat-drawer">
        <div class="chat-drawer-header">
            <h3 id="chatDrawerTitle">与智能体对话</h3>
            <button class="close-btn" onclick="closeAgentChatDrawer()">&times;</button>
        </div>
        <div class="chat-drawer-body" id="chatDrawerMessages">
            </div>
        <div class="chat-drawer-footer">
            <div class="chat-input-area">
                <input type="text" id="chatDrawerMessageInput" placeholder="输入消息...">
                <button class="modal-btn modal-btn-primary" onclick="sendDrawerChatMessage()">发送</button>
            </div>
        </div>
    </div>

    <!-- Create DWF MCP Modal with Tree Configuration -->
    <div id="createMcpModal" class="modal-overlay">
        <div class="modal-content large">
            <div class="modal-header">
                <h3>配置 DWF MCP</h3>
                <button class="close-btn" onclick="closeCreateMcpModal()">&times;</button>
            </div>
            <form id="createMcpForm">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="mcpName">MCP 名称</label>
                        <input type="text" id="mcpName" name="mcpName" required>
                    </div>

                    <div class="form-group">
                        <p class="form-section-title">DWF MCP 能力配置</p>
                        <div class="tree-view-container">
                            <ul class="tree-view" id="mcpCapabilitiesTree">
                                <li>
                                    <label><input type="checkbox" name="mcp_capability_category" value="entity_ops_all" onchange="toggleParentCheckbox(this, 'entity_ops_children')"> 实体类操作</label>
                                    <ul id="entity_ops_children">
                                        <li><label><input type="checkbox" name="mcp_capability" value="entity_create"> 创建实体类</label></li>
                                        <li><label><input type="checkbox" name="mcp_capability" value="entity_query"> 查询实体类</label></li>
                                        <li><label><input type="checkbox" name="mcp_capability" value="entity_analyze"> 数据分析</label></li>
                                        <li><label><input type="checkbox" name="mcp_capability" value="entity_update"> 更新实体</label></li>
                                        <li><label><input type="checkbox" name="mcp_capability" value="entity_delete"> 删除实体</label></li>
                                    </ul>
                                </li>
                                <li>
                                    <label><input type="checkbox" name="mcp_capability_category" value="form_ops_all" onchange="toggleParentCheckbox(this, 'form_ops_children')"> 表单类操作</label>
                                    <ul id="form_ops_children">
                                        <li><label><input type="checkbox" name="mcp_capability" value="form_submit"> 提交表单</label></li>
                                        <li><label><input type="checkbox" name="mcp_capability" value="form_query_status"> 查询表单状态</label></li>
                                    </ul>
                                </li>
                                <li>
                                    <label><input type="checkbox" name="mcp_capability_category" value="script_ops_all" onchange="toggleParentCheckbox(this, 'script_ops_children')"> 脚本类操作</label>
                                    <ul id="script_ops_children">
                                        <li><label><input type="checkbox" name="mcp_capability" value="script_execute"> 执行脚本</label></li>
                                        <li><label><input type="checkbox" name="mcp_capability" value="script_get_logs"> 获取脚本日志</label></li>
                                    </ul>
                                </li>
                            </ul>
                        </div>
                    </div>

                    <div class="form-group">
                         <p class="form-section-title">数据范围配置 (当前DWF实例: <span id="currentConfigDwfInstanceName">未选择</span>)</p>
                         <div class="tree-view-container">
                            <ul class="tree-view" id="dataScopeTree">
                                <li>
                                    <label><input type="checkbox" name="data_scope_entity_all" value="dwf_instance_current_entity_all" onchange="toggleParentCheckbox(this, 'data_scope_entity_children')"> 实体类 (全部)</label>
                                    <ul id="data_scope_entity_children">
                                        <li><label><input type="checkbox" name="data_scope_entity" value="entity_type_workorder"> 工单类</label></li>
                                        <li><label><input type="checkbox" name="data_scope_entity" value="entity_type_device"> 设备类</label></li>
                                        <li><label><input type="checkbox" name="data_scope_entity" value="entity_type_engineer"> 工程师类</label></li>
                                        <li><label><input type="checkbox" name="data_scope_entity" value="entity_type_asset"> 资产类</label>
                                            <ul>
                                                <li><label><input type="checkbox" name="data_scope_asset_subtype" value="asset_subtype_server"> 服务器</label></li>
                                                <li><label><input type="checkbox" name="data_scope_asset_subtype" value="asset_subtype_network"> 网络设备</label></li>
                                            </ul>
                                        </li>
                                    </ul>
                                </li>
                                 <li>
                                    <label><input type="checkbox" name="data_scope_form_all" value="dwf_instance_current_form_all" onchange="toggleParentCheckbox(this, 'data_scope_form_children')"> 表单类 (全部)</label>
                                     <ul id="data_scope_form_children">
                                        <li><label><input type="checkbox" name="data_scope_form" value="form_type_incident"> 故障报修单</label></li>
                                        <li><label><input type="checkbox" name="data_scope_form" value="form_type_request"> 服务请求单</label></li>
                                    </ul>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="modal-btn modal-btn-secondary" onclick="closeCreateMcpModal()">取消</button>
                    <button type="button" class="modal-btn modal-btn-primary" onclick="saveMcpConfiguration()">保存并运行MCP</button>
                </div>
            </form>
        </div>
    </div>

    <!-- MCP Log Modal -->
    <div id="mcpLogModal" class="modal-overlay">
        <div class="modal-content large">
            <div class="modal-header">
                <h3 id="mcpLogModalTitle">MCP 服务日志</h3>
                <button class="close-btn" onclick="closeMcpLogModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div id="mcpLogContent">
                    <!-- Logs will be displayed here -->
                    加载日志中...
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="modal-btn modal-btn-secondary" onclick="closeMcpLogModal()">关闭</button>
            </div>
        </div>
    </div>


    <script>
        // --- Modal & Drawer Getters ---
        const addEnvModal = document.getElementById('addEnvModal');
        const addEnvForm = document.getElementById('addEnvForm');

        const agentChatOverlay = document.getElementById('agentChatOverlay');
        const agentChatDrawer = document.getElementById('agentChatDrawer');
        const chatDrawerTitle = document.getElementById('chatDrawerTitle');
        const chatDrawerMessagesDiv = document.getElementById('chatDrawerMessages');
        const chatDrawerMessageInput = document.getElementById('chatDrawerMessageInput');

        const createMcpModal = document.getElementById('createMcpModal');
        const createMcpForm = document.getElementById('createMcpForm');
        const currentConfigDwfInstanceNameSpan = document.getElementById('currentConfigDwfInstanceName');

        const mcpLogModal = document.getElementById('mcpLogModal');
        const mcpLogModalTitle = document.getElementById('mcpLogModalTitle');
        const mcpLogContent = document.getElementById('mcpLogContent');

        let currentAgentContext = {};

        // --- Gemini API Call Function ---
        async function callGeminiApi(prompt) {
            const apiKey = "";
            const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;
            const chatHistory = [{ role: "user", parts: [{ text: prompt }] }];
            const payload = { contents: chatHistory };

            try {
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });
                if (!response.ok) {
                    const errorBody = await response.text();
                    console.error("Gemini API Error HTTP Status:", response.status, "Body:", errorBody);
                    return `抱歉，调用AI服务时出错 (HTTP ${response.status})。请稍后再试。`;
                }
                const result = await response.json();
                if (result.candidates && result.candidates.length > 0 &&
                    result.candidates[0].content && result.candidates[0].content.parts &&
                    result.candidates[0].content.parts.length > 0) {
                    return result.candidates[0].content.parts[0].text;
                } else {
                    console.error("Gemini API Error: Unexpected response structure", result);
                    return "抱歉，AI服务返回了意外的响应。";
                }
            } catch (error) {
                console.error("Error calling Gemini API:", error);
                return "抱歉，连接AI服务时发生网络错误。";
            }
        }

        // --- Environment Management Functions ---
        function openAddEnvModal() {
            addEnvForm.reset();
            document.getElementById('envDescription').value = '';
            addEnvModal.classList.add('active');
        }
        function closeAddEnvModal() {
            addEnvModal.classList.remove('active');
        }
        async function generateEnvironmentDescription() {
            const envName = document.getElementById('envName').value;
            const envKey = document.getElementById('envKey').value;
            const generateBtn = document.getElementById('generateEnvDescBtn');
            const loadingIndicator = generateBtn.querySelector('.loading-indicator');

            if (!envName && !envKey) {
                alert("请输入环境名称或环境Key以生成描述。");
                return;
            }
            generateBtn.disabled = true;
            loadingIndicator.style.display = 'inline-block';
            generateBtn.childNodes[0].nodeValue = "正在生成... ";
            const prompt = `为一个名为 "${envName}" (Key: "${envKey}") 的DWF环境生成一个简洁的描述 (不超过50字)。`;
            const description = await callGeminiApi(prompt);
            document.getElementById('envDescription').value = description.replace(/^抱歉，.*$/, '');
            generateBtn.disabled = false;
            loadingIndicator.style.display = 'none';
            generateBtn.childNodes[0].nodeValue = "✨ 生成描述 ";
        }
        function saveNewEnvironment() {
            console.log('新环境数据已收集');
            closeAddEnvModal();
        }
        function testConnect() { alert('测试连接功能'); }
        function editEnvironment(envId) { alert(`编辑环境: ${envId}`); }
        function deleteEnvironment(envId) { if (confirm(`确定要删除环境 ${envId} 吗？`)) { alert(`删除环境: ${envId}`); } }
        function setDefaultEnvironment(envIdToSetDefault) {
            document.querySelectorAll('.env-card').forEach(card => {
                card.classList.remove('default-env');
                const button = card.querySelector('.set-default-btn');
                if (button) { button.innerHTML = '<span class="icon">✩</span>设为默认'; }
            });
            const selectedCard = document.getElementById(`env-card-${envIdToSetDefault}`);
            if (selectedCard) {
                selectedCard.classList.add('default-env');
                const button = selectedCard.querySelector('.set-default-btn');
                if (button) { button.innerHTML = '<span class="icon">⭐</span>已为默认'; }
                console.log(`环境 ${envIdToSetDefault} 已设为默认.`);
            }
        }

        // --- Agent Marketplace Functions ---
        function createAgent() { alert('创建智能体功能'); }
        function configureAgent(agentId) { alert(`配置智能体: ${agentId}`); }
        function deleteAgent(agentId) { if (confirm(`确定要删除智能体 ${agentId} 吗？`)) { alert(`删除智能体: ${agentId}`); } }

        function openAgentChatDrawer(agentId, agentName, agentType) {
            currentAgentContext = { id: agentId, name: agentName, type: agentType };
            chatDrawerTitle.textContent = `与 ${agentName} (${agentType}) 对话`;
            chatDrawerMessagesDiv.innerHTML = '';
            addMessageToDrawerChat("你好！我是" + agentName + "，有什么可以帮助你的吗？", "agent");
            agentChatOverlay.classList.add('active');
            agentChatDrawer.classList.add('active');
            chatDrawerMessageInput.focus();
        }
        function closeAgentChatDrawer() {
            agentChatOverlay.classList.remove('active');
            agentChatDrawer.classList.remove('active');
        }
        function addMessageToDrawerChat(message, sender) {
            const messageDiv = document.createElement('div');
            messageDiv.classList.add('chat-message', sender);
            messageDiv.textContent = message;
            chatDrawerMessagesDiv.appendChild(messageDiv);
            chatDrawerMessagesDiv.scrollTop = chatDrawerMessagesDiv.scrollHeight;
        }
        async function sendDrawerChatMessage() {
            const userMessage = chatDrawerMessageInput.value.trim();
            if (!userMessage) return;
            addMessageToDrawerChat(userMessage, "user");
            chatDrawerMessageInput.value = '';
            addMessageToDrawerChat("正在思考中...", "agent chat-message loading");
            const prompt = `你是一个名为 "${currentAgentContext.name}" 的 ${currentAgentContext.type} AI智能体。用户说: "${userMessage}" 请回复用户。`;
            const agentResponse = await callGeminiApi(prompt);
            const loadingMessageElement = chatDrawerMessagesDiv.querySelector('.chat-message.loading');
            if (loadingMessageElement) { loadingMessageElement.remove(); }
            addMessageToDrawerChat(agentResponse, "agent");
        }
        chatDrawerMessageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') { sendDrawerChatMessage(); }
        });

        // --- MCP Management Functions ---
        function openCreateMcpModal() {
            createMcpForm.reset();
            const selectedDwfEnv = document.getElementById('mcpEnvSelect');
            if (selectedDwfEnv && currentConfigDwfInstanceNameSpan) {
                currentConfigDwfInstanceNameSpan.textContent = selectedDwfEnv.options[selectedDwfEnv.selectedIndex].text;
            } else if (currentConfigDwfInstanceNameSpan) {
                currentConfigDwfInstanceNameSpan.textContent = "未选择";
            }
            createMcpModal.classList.add('active');
        }
        function closeCreateMcpModal() {
            createMcpModal.classList.remove('active');
        }
        function saveMcpConfiguration() {
            const mcpName = document.getElementById('mcpName').value;
            if (!mcpName.trim()) {
                alert("请输入MCP名称。 (Please enter MCP Name.)");
                return;
            }
            const selectedCapabilities = [];
            document.querySelectorAll('#mcpCapabilitiesTree input[type="checkbox"]:checked').forEach(checkbox => {
                if (!checkbox.name.includes('_all')) {
                     selectedCapabilities.push(checkbox.value);
                }
            });
            const selectedDataScopes = [];
            document.querySelectorAll('#dataScopeTree input[type="checkbox"]:checked').forEach(checkbox => {
                 if (!checkbox.name.includes('_all')) {
                    selectedDataScopes.push(checkbox.value);
                 }
            });
            const currentDwfInstance = document.getElementById('mcpEnvSelect').value;
            const mcpConfig = {
                name: mcpName,
                dwfInstanceTarget: currentDwfInstance,
                capabilities: selectedCapabilities,
                dataScopes: selectedDataScopes
            };
            console.log("保存的DWF MCP配置 (Saved DWF MCP Configuration):", mcpConfig);
            alert(`DWF MCP "${mcpName}" 配置已收集。`);
            closeCreateMcpModal();
        }
        function configureMCP(mcpId) {
            alert(`配置MCP: ${mcpId} (此功能将打开预填表单)。`);
            openCreateMcpModal();
        }
        function deleteMCP(mcpId) { if (confirm(`确定要删除MCP ${mcpId} 吗？`)) { alert(`删除MCP: ${mcpId}`); } }
        function toggleMcpStatus(mcpId, isEnabled) {
            const statusText = isEnabled ? '启用' : '禁用';
            console.log(`MCP 服务 ${mcpId} 状态已更改为: ${statusText}`);
        }
        function copyToClipboard(elementId) {
            const textToCopySpan = document.getElementById(elementId);
            if (!textToCopySpan) return;
            const textToCopy = textToCopySpan.textContent;
            const textArea = document.createElement("textarea");
            textArea.value = textToCopy;
            textArea.style.position = "fixed";
            textArea.style.left = "-9999px";
            document.body.appendChild(textArea);
            textArea.select();
            try {
                document.execCommand('copy');
                alert('SSE URL 已复制到剪贴板！');
            } catch (err) {
                console.error('无法复制文本: ', err);
                alert('复制失败，请手动复制。');
            }
            document.body.removeChild(textArea);
        }
        // New function for viewing MCP Logs
        function viewMcpLogs(mcpId) {
            if (!mcpLogModal || !mcpLogModalTitle || !mcpLogContent) {
                console.error("Log modal elements not found!");
                return;
            }
            mcpLogModalTitle.textContent = `MCP 服务日志: ${mcpId}`;
            // Placeholder logs - replace with actual log fetching logic
            mcpLogContent.textContent = `[${new Date().toLocaleString()}] INFO: MCP Service ${mcpId} started.\n`;
            mcpLogContent.textContent += `[${new Date().toLocaleString()}] DEBUG: Attempting to connect to DWF instance...\n`;
            mcpLogContent.textContent += `[${new Date().toLocaleString()}] INFO: Connection successful.\n`;
            mcpLogContent.textContent += `[${new Date().toLocaleString()}] EVENT: Received new SSE client connection from 127.0.0.1.\n`;
            mcpLogContent.textContent += `[${new Date().toLocaleString()}] TOOL_CALL: entity_query invoked with params: {...}\n`;
            mcpLogContent.textContent += `[${new Date().toLocaleString()}] TOOL_RESPONSE: Query successful, 5 entities found.\n`;

            mcpLogModal.classList.add('active');
        }
        function closeMcpLogModal() {
            if (mcpLogModal) {
                mcpLogModal.classList.remove('active');
            }
        }


        // --- Tab Switching Logic ---
        function switchTab(tabName) {
            const tabContents = document.querySelectorAll('.tab-content');
            tabContents.forEach(content => { content.style.display = 'none'; });
            const navLinks = document.querySelectorAll('.nav-link');
            navLinks.forEach(link => { link.classList.remove('active'); });
            const currentTabContent = document.getElementById(tabName);
            if (currentTabContent) { currentTabContent.style.display = 'block'; }
            let activeLink = null;
            if (typeof event !== 'undefined' && event && event.currentTarget && event.currentTarget.classList.contains('nav-link')) {
                 activeLink = event.currentTarget;
            } else if (typeof event !== 'undefined' && event && event.target) {
                const clickedLink = event.target.closest('.nav-link');
                if (clickedLink) { activeLink = clickedLink; }
            }
            if (!activeLink) { activeLink = document.querySelector(`.nav-link[onclick*="switchTab('${tabName}')"]`); }
            if (activeLink) { activeLink.classList.add('active'); }
        }

        document.addEventListener('DOMContentLoaded', function() {
            const defaultTabName = 'environment';
            switchTab(defaultTabName);
            const defaultNavLink = document.querySelector(`.nav-link[onclick*="switchTab('${defaultTabName}')"]`);
            if (defaultNavLink) {
                document.querySelectorAll('.nav-menu .nav-link').forEach(link => link.classList.remove('active'));
                defaultNavLink.classList.add('active');
            }
            const firstEnvCard = document.querySelector('.env-card');
            if (firstEnvCard && firstEnvCard.id) {
                 const firstEnvId = firstEnvCard.id.replace('env-card-', '');
                 setDefaultEnvironment(firstEnvId);
            }
            [addEnvModal, agentChatOverlay, createMcpModal, mcpLogModal].forEach(overlay => { // Added mcpLogModal
                if (overlay) {
                    overlay.addEventListener('click', function(event) {
                        if (event.target === overlay) {
                            if(overlay.id === 'addEnvModal') closeAddEnvModal();
                            if(overlay.id === 'agentChatOverlay') closeAgentChatDrawer();
                            if(overlay.id === 'createMcpModal') closeCreateMcpModal();
                            if(overlay.id === 'mcpLogModal') closeMcpLogModal(); // Added
                        }
                    });
                }
            });

            // Tree view parent checkbox logic
            function toggleParentCheckbox(parentCheckbox, childrenListId) {
                const childList = document.getElementById(childrenListId);
                if (childList) {
                    childList.querySelectorAll('input[type="checkbox"]').forEach(childCheckbox => {
                        childCheckbox.checked = parentCheckbox.checked;
                    });
                }
            }

            document.querySelectorAll('.tree-view input[name$="_all"]').forEach(parentCheckbox => {
                parentCheckbox.addEventListener('change', function() {
                    const childrenListId = this.closest('li').querySelector('ul')?.id;
                    if (childrenListId) {
                        toggleParentCheckbox(this, childrenListId);
                    }
                });
            });
             document.querySelectorAll('.tree-view ul input[type="checkbox"]').forEach(childCheckbox => {
                childCheckbox.addEventListener('change', function() {
                    const parentLi = this.closest('ul').closest('li');
                    if (parentLi) {
                        const parentCheckbox = parentLi.querySelector('input[name$="_all"]');
                        const siblings = Array.from(this.closest('ul').querySelectorAll('input[type="checkbox"]'));
                        if (parentCheckbox) {
                            parentCheckbox.checked = siblings.every(cb => cb.checked);
                            parentCheckbox.indeterminate = !siblings.every(cb => cb.checked) && siblings.some(cb => cb.checked);
                        }
                    }
                });
            });

        });

        // --- Ripple Effect for Buttons ---
        document.querySelectorAll('.create-btn, .gemini-btn, .action-btn, .set-default-btn, .modal-btn').forEach(btn => {
            btn.addEventListener('click', function(e) {
                if (this.classList.contains('nav-link')) return;
                if (this.closest('.modal-content') && (this.textContent === '取消' || this.textContent.includes('保存'))) {}
                const ripple = document.createElement('span');
                const rect = this.getBoundingClientRect();
                const size = Math.max(rect.width, rect.height);
                const x = e.clientX - rect.left - size / 2;
                const y = e.clientY - rect.top - size / 2;
                Object.assign(ripple.style, {
                    width: `${size}px`, height: `${size}px`, left: `${x}px`, top: `${y}px`,
                    position: 'absolute', borderRadius: '50%', transform: 'scale(0)',
                    animation: 'ripple 0.6s linear', pointerEvents: 'none',
                    background: 'rgba(255, 255, 255, 0.4)'
                });
                if (this.classList.contains('delete-btn')) ripple.style.background = 'rgba(239, 68, 68, 0.3)';
                else if (this.classList.contains('edit-btn')) ripple.style.background = 'rgba(59, 130, 246, 0.3)';
                else if (this.classList.contains('debug-btn')) ripple.style.background = 'rgba(16, 185, 129, 0.3)';
                else if (this.classList.contains('log-btn')) ripple.style.background = 'rgba(245, 158, 11, 0.3)';
                else if (this.classList.contains('set-default-btn') && this.closest('.env-card.default-env')) ripple.style.background = 'rgba(255, 255, 255, 0.3)';
                else if (this.classList.contains('set-default-btn')) ripple.style.background = 'rgba(55, 65, 81, 0.2)';
                else if (this.classList.contains('modal-btn-primary') || this.classList.contains('gemini-btn')) ripple.style.background = 'rgba(255, 255, 255, 0.3)';
                else if (this.classList.contains('modal-btn-secondary')) ripple.style.background = 'rgba(55, 65, 81, 0.2)';
                this.style.position = 'relative'; this.style.overflow = 'hidden';
                this.appendChild(ripple);
                setTimeout(() => { ripple.remove(); }, 600);
            });
        });
        const styleSheet = document.createElement('style');
        styleSheet.textContent = `@keyframes ripple { to { transform: scale(4); opacity: 0; } }`;
        document.head.appendChild(styleSheet);
    </script>
</body>
</html>
